package com.sptpc.learnspring.service;

import com.sptpc.learnspring.common.OrderState;
import com.sptpc.learnspring.model.Drink;
import com.sptpc.learnspring.model.Order;
import com.sptpc.learnspring.repository.OrderRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;


@Slf4j
@Service
public class OrderService {
    @Autowired
    private OrderRepository orderRepository;


    public Order saveOrder(String customer, Drink... drinks) {
        Order order = Order.builder()
                        .customer(customer)
                        .items(new ArrayList<>(Arrays.asList(drinks)))
                        .state(OrderState.INIT).build();
        return orderRepository.save(order);
    }

    public Order updateOrder(long orderId,Drink deleteDrink) {
        Order order = orderRepository.findById(orderId).get();
        List<Drink> newItems = order.getItems().stream()
                                .filter(drink -> drink.getId() != deleteDrink.getId())
                                .collect(Collectors.toList());
        order.setItems(newItems);
        return orderRepository.saveAndFlush(order);
    }

    public boolean changeState(Order oldOrder, OrderState state) {
        if (state.compareTo(oldOrder.getState()) <=0) {
            log.warn("状态不能{}从到{}",oldOrder.getState(),state);
            return false;
        }
        oldOrder.setState(state);
        Order order = orderRepository.saveAndFlush(oldOrder);
        log.info("更改后到订单:{}",order);
        return true;
    }


    public Order getOrder(String customer,int index) {
        List<Order> orders = orderRepository.findOrdersByCustomerLike(customer);
        return orders.get(index);
    }

    public List<Order> getOrders(String customer) {
        return orderRepository.findOrdersByCustomerLike(customer);
    }

    public void deleteOrder(long orderId) {
        orderRepository.deleteById(orderId);
    }
}
